package com.yhb.third.leshua;

import lombok.extern.log4j.Log4j;
import lombok.var;
import me.edzh.spring.bootstrap.model.Tuple;
import me.edzh.spring.bootstrap.utils.JSONUtil;
import me.edzh.spring.bootstrap.utils.ObjectMapperFactory;
import me.edzh.spring.bootstrap.utils.ResultCode;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;
import okhttp3.*;
import org.apache.commons.codec.binary.Hex;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

@Log4j
public class HttpUtil {

    private static final String privateKeyStr = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCkaR07Av4gdpDSmgMuHKxqFSxK1GL9lkZRCINPvF7qCPQHs84UgjIF0NgC6UnU3b3lxCDTACgSPE1a+RlxnW2ch9p++nxFApfHbY1ZLx4N9SI3ol0lp46yt6LZcYSRbpNSy6t/C+06owabgOoIIxk2xQxeFuxFVomzvjEaCbbTQtGqWVpkMY6ONPyPzkctoDw4FooSYt6728yF9E3RK4Oxb0KEkmeMYdYSp/014hghoSdEQ9/p01q6qkszebxgULiUNt8c4YLvc3X0dj1/IdI4dYWhQfyhIh7bpltVSwya2g424WQfhd9KxMdJu5eocFksYEEhXshVnDObpe2bbNpLAgMBAAECggEBAIU+LxNZPI0gqgQUD0m6sTyUBj5q3AL6W+hmRs1DM4TmVqc7YGOclF/EPpw1ZsGeJ71jctquAMuulV6KDMXYOTIno7tO05G2JT3ZmjlSB0B2jxGZg3X10p8iVld1OWQHwlvSdh1TlCH2Z291TbXkhBWwInLKjxcuqBDErdSVVNbmuMlsQwP0Cros/VctB1YZpT4i4UVg8hl8mjRHXPuPWMt0Q8j3k20cEcotDAJ4A7pXIWUXnQCyiSg6njAnU8Ak8cu840Q/kSmaPvL94N4hNJpA/AAzoNvUhh92Mlmq+9Mic+sdnsnWpg/xlKg0DW03dxI6JmAwm2dBYq0K4JO9SCECgYEA95fE+S33g0liVQd14DjQEXxaiCm7iQ4sAHDq1U18K0TDz8HSQ0m60s8MV5jonsQ/ynWM+syD2O+0f2jf2MYPEkCHQN8l77ZB4H61/UN6btu1mpIqa3J1DmdbrgAD0NVrnCe89EExm55MRFMBcGO7dMDXmjo7stHwBrTjsFDDXFsCgYEAqf5F6NGrKzz/J3i3ppuBTUdY7qRyLuZyitwVCYvBt5qwoOfMqqy9uEePpPqylPUBfHG+PDkoTXMfhlyWxp97kiW/uye3Vh7diBLsoOaxYsvRIP4tC1rx8OhzNqS367AT792iaSICHT8b0SOT7a8AKxOeFokEybyBUmcv/ZulnNECgYEApMEvZ4i4/XnlnyM5wxzLB/ex3o22pzrw+NIq0gmfqMM3cZZOLkxvrzvrwJaVpKB+umCCkZlp2v+XInlNC1iwSrr5xac3/U1QhOyMeZ1faUl2jQbah2lAj3cjwKNt5pc95kljKT4Ansc1hPmfKYSUBtsUHSLG+vVMPYo9QORdO6UCgYAFLWVbrecUrgrnXNnbDSlm/SFMQ13m58XdTM6nN8ZynRd8DxNAr3onvqY1VB1URBIDhENS+jqsATGYmgFNk1XkIZoxTQhcaxw8JLdoPx5v790ysAsXKXHs8Gdx5ppjZz10NL/Zi9ucoGtsdzTuLEJJDZPnA81Nh5w4skPX6YGlwQKBgB3lM2SltE4q1WHHCT2m/4gGoEEuIn07QO6F0+AjthpH2rZAZqUJDRRAqGU3jRcjbnxrPF9fo7DqE0RGjstSigm9+Kg79d0tRUzh0TMms4t5RqjUjiS+6nrfcypXfXektxjF3o0LpEdMFjaeLMSiLBGA8HjUAg8FG3o/XzwlHy0F";
    private static final String KEY = "5653180@ldjfk5e6r8t59t5df6re7t3r";
    private static final String AGENT_ID = "5653180";

    private static OkHttpClient client = new OkHttpClient.Builder().build();
    private static final String baseUrl = "https://happypay.leshuazf.com/happypay/";
    public static <T> T request(String url, Map<String, String> params, Class<T> returnClazz) {
//        FormBody.Builder builder =  new FormBody.Builder();
        params.put("agentId", AGENT_ID);
//        for(String s : params.keySet()) {
//            builder.add(s, params.get(s));
//        }


        var signObj = sign(params);
//        builder.add("sign", signObj.getValue2());
//        RequestBody body = builder.build();

        try {

            url += "?";
            for (Map.Entry<String, Object> entry : signObj.getValue1().entrySet()) {
                url += entry.getKey() + "=" + URLEncoder.encode(entry.getValue().toString(), "utf-8") + "&";
            }

            url += "sign=" + signObj.getValue2();
            log.info("request to: " + url);

            Request request = new Request.Builder()
                    .url(baseUrl + url)
                    .post(new FormBody.Builder().build())
                    .build();


            Response resp = client.newCall(request).execute();
            String rawResp = resp.body().string();
            log.info("raw body:\n" + rawResp);
            String respBody = RSADecryptUtil.decrypt(rawResp.replace("\n", "").replace("\r", ""), privateKeyStr);
            log.info("result body:\n" + respBody);
            return JSONUtil.parseJson(respBody, returnClazz);
        } catch (Exception e) {
            log.info("request err", e);
            throw new ServiceException(ResultCode.ERROR_INTERNAL_DATA_CODE, "err", e);
        }
    }

    private static Tuple<TreeMap<String, Object>, String> sign (Map<String, String> params) {
        TreeMap<String, Object> sortedMap = new TreeMap<>(params);
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
//            log.info("key:" + entry.getKey() + "  value:" + entry.getValue().toString());
            sb.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
        }

        sb.append("key=" + KEY);

        return new Tuple<>(sortedMap, DigestUtil.getMd5(sb.toString()));

    }
}
